package gps.monitor.jt809server.network.netty;

import gps.monitor.jt809server.protocol.Jt809Keywords;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.EmptyByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.ByteBuffer;
import java.util.List;

/**
 * 可用 DelimiterBasedFrameDecoder 代替
 * @author cyq
 * @date 2021/11/5
 * @desc talk is cheep,show me the code
 */
public class SimpleJt809NettyDecoder extends ByteToMessageDecoder {

    private static final int MaxDecodeCountInARound = 100;

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        //ByteBufUtil
        int packageCount = 0;
        while (byteBuf.isReadable() && byteBuf.readByte() == Jt809Keywords.K5B) {

            int datastart = byteBuf.readerIndex();
            int maxLen = byteBuf.writerIndex() - datastart;
            int dataLen = 0;
            boolean ended = false;
            while (maxLen > dataLen) {
                ended = byteBuf.getByte(datastart + dataLen) == Jt809Keywords.K5D;
                if (ended) break;
                ++dataLen;
            }
            if (ended) {
                //String hexdata = ByteBufUtil.hexDump(byteBuf, datastart, dataLen);
                ByteBuf data = byteBuf.readBytes(dataLen);
                byteBuf.readByte();
                //ByteBuf data = byteBuf.slice(datastart,dataLen);
                //byteBuf.readBytes(dataLen+1);
                channelHandlerContext.fireChannelRead(data);

                if (++packageCount > MaxDecodeCountInARound) break;
            }else {
                break;
            }
        }
    }
}
